package com.ruoyi.riskrule.config;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.bizsys.domain.*;
import com.ruoyi.bizsys.service.*;
import com.ruoyi.bizsys.utils.BizConstants;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.utils.Func;
import com.ruoyi.common.utils.business.CheckAccountNameUtil;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.extdata.common.config.RuleConfig;
import com.ruoyi.riskrule.config.common.RuleUtils;
import com.ruoyi.riskrule.service.ILoanFieldService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;

import java.math.BigDecimal;
import java.util.Optional;

/**
 * 绑卡提额参数
 */
@Slf4j
@Configuration
@AllArgsConstructor
public class BindCardParamsLoader {

    private ICustBankCardService bankCardService;

    private ILoanFieldService loanService;

    private RuleConfig ruleConfig;

    private IIncreasedLimitLogService increasedLimitLogService;

    private IRepaymentOrderService repaymentOrderService;

    private IRealNameAuthService realNameAuthService;

    private ICustBindCardLogService custBindCardLogService;

    private ICreditAccountService creditAccountService;

    private ICustomerInfoService customerInfoService;

    public RuleIn initRuleInParam(String custNo) {

        RealNameAuth realNameAuth = realNameAuthService.selectRealNameAuthByCustNo(custNo);
        CustBindCardLog cardLog = custBindCardLogService.getOne(new QueryWrapper<CustBindCardLog>().eq("cust_no", realNameAuth.getCustNo()).last("order by id desc limit 1;"));

        RuleIn ruleIn = new RuleIn();
        //存User,和历史保存一致...
        ruleIn.setCustNo(customerInfoService.getUserByCustNo(custNo));
        //进件id
        ruleIn.setEntryId(IdUtils.reqId());
        //产品编号
        ruleIn.setProductCode(ruleConfig.getProductCode());
        //决策流
        ruleIn.setRunType(ruleConfig.getRunType());
        //工作流编号
        ruleIn.setWorkflowCode(RuleConfig.RULE_WORK_FLOW_CODE_LIMIT_ACTIVE_LIMIT);
        //业务类型
        ruleIn.setOperType("6");
        //总绑定银行卡数 bindcradno
        ruleIn.setBindcardno(this.getBindcardno(custNo) + "");
        //已绑定有效银行卡数
        ruleIn.setCardineffectnum(this.getCardineffectnum(custNo) + "");
        //绑卡提额总金额
        ruleIn.setSumbindcredit(Optional.ofNullable(getSumbindcredit(custNo)).orElse(BigDecimal.ZERO).toString());
        //绑卡提额次数
        ruleIn.setCountbindcredit(this.getCountbindcredit(custNo) + "");
        //代扣成功银行卡数
        ruleIn.setWithholdcardnum(repaymentOrderService.getWithholdCardCount(custNo) + "");
        //卡片账户姓名是否匹配
        ruleIn.setAccountnamematch(getAccountnamematch(realNameAuth,cardLog) + "");
        //当前逾期天数
        ruleIn.setCurrentmaxyuqi(Optional.ofNullable(loanService.getCurrentOverdue(custNo)).orElse(0) + "");
        //BVN
        ruleIn.setBvnNumber(realNameAuth.getBvnAccount());
        //绑卡流水号
        ruleIn.setAdjustSerialNo(cardLog.getBindSerialNo());
        //当前额度
        ruleIn.setCreditLine(creditAccountService.getLatestQuota(custNo).toString());

        ruleIn.setRecFlag(UserConstants.BUSINESS_NOT_NORMAL);
        ruleIn.setState(UserConstants.BUSINESS_NORMAL);
        return afterFormat(ruleIn);
    }

    /**
     * 总绑定银行卡数
     *
     * @param custNo
     * @return
     */
    private int getBindcardno(String custNo) {
        return bankCardService.count(new QueryWrapper<CustBankCard>().eq("cust_no", custNo));
    }

    /**
     * 有效期三个月以上的银行卡数
     *
     * @return
     */
    public int getCardineffectnum(String custNo) {
        return bankCardService.count(new QueryWrapper<CustBankCard>().eq("cust_no", custNo).last("and TIMESTAMPDIFF(DAY,NOW(),STR_TO_DATE(CONCAT(expire_date,'01'),'%Y%m%d'))  > 90"));
    }

    /**
     * 绑卡提额总金额
     *
     * @return
     */
    private BigDecimal getSumbindcredit(String custNo) {
        return increasedLimitLogService.increasedSumByType(custNo, Constants.RaiseLimit.ADJUST_TYPE_BANK_CARD);
    }

    /**
     * 绑卡成功提额次数
     *
     * @return
     */
    private int getCountbindcredit(String custNo) {
        QueryWrapper<IncreasedLimitLog> eq = new QueryWrapper<IncreasedLimitLog>().eq("cust_no", custNo).eq("adjust_type", Constants.RaiseLimit.ADJUST_TYPE_BANK_CARD);
        return increasedLimitLogService.count(eq);
    }

    /**
     * 卡片账户姓名是否匹配
     *
     * @return
     */
    private int getAccountnamematch(RealNameAuth realNameAuth,CustBindCardLog cardLog) {
        if (Func.isEmpty(cardLog) || Func.isEmpty(cardLog.getAccountName())) {
            return -1;
        }
        return CheckAccountNameUtil.verifyName(realNameAuth.getFullName(), cardLog.getAccountName()) ? 1 : 0;
    }

    public RuleIn afterFormat(RuleIn ruleIn) {
        ruleIn.setEntrytime(com.ruoyi.riskrule.constants.Constants.DEFAULT_TIME);
        return RuleUtils.afterFormat(ruleIn);
    }


}
